/*
 * ptrlist.hpp
 *
 *  Created on: 2018-7-25
 *      Author: work
 */

#ifndef DM_PTRLIST_H_
#define DM_PTRLIST_H_

#include <list>

namespace dm {

template<typename T>
class TCPtrList {
    TCPtrList( const TCPtrList& p );
    TCPtrList& operator=( const TCPtrList& p );
public:
    TCPtrList():m_e(){
    }

    ~TCPtrList(){
        clear();
    }

    inline unsigned int size()const{
        return m_e.size();
    }

    inline void append( T* e ){
        m_e.push_back(e);
    }

    T* element( int idx ){
        std::list<T*>::iterator it = m_e.begin();
        while( idx>0 ){
            ++it;
            if( it==m_e.end() )
                return NULL;

            --idx;
        }

        if( it!=m_e.end() ){
            return *it;
        }else{
            return NULL;
        }
    }

    const T* element( int idx )const{
        std::list<T*>::const_iterator it = m_e.begin();
        while( idx>0 ){
            ++it;
            if( it==m_e.end() )
                return NULL;

            --idx;
        }

        if( it!=m_e.end() ){
            return *it;
        }else{
            return NULL;
        }
    }

    void remove( int idx ){
        std::list<T*>::iterator it = m_e.begin();
        while( idx>0 ){
            ++it;
            if( it==m_e.end() )
                return;

            --idx;
        }

        if( it!=m_e.end() ){
            if( *it )
                delete (*it);
            m_e.erase(it);
        }
    }

    void clear(){
        for( std::list<T*>::iterator it=m_e.begin();it!=m_e.end();++it ){
            if( *it )
                delete (*it);
        }
        m_e.clear();
    }

private:
    std::list<T*> m_e;
};

} /* namespace Dm */
#endif
